﻿using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using ZQNB.Common;
using ZQNB.Common.Models;
using ZQNB.Common.Web;

namespace ZQNB.AppLib.Cloud.Helpers
{
    /// <summary>
    /// 要求云中心管理员账号必须登录(基于Session)
    /// 安全性衡量？
    /// </summary>
    public class CloudLogOnAttribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            bool isChildAction = MvcHelper.IsChildAction(filterContext);
            if (isChildAction)
            {
                return;
            }

            bool isAjaxRequest = MvcHelper.IsAjaxRequest(filterContext);
            if (isAjaxRequest)
            {
                JsonResult jsonResult = new JsonResult();
                jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                jsonResult.Data = new MessageResult() { Message = "需要云中心管理员进行登录", Success = false }; ;
                filterContext.Result = jsonResult;
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult("Cloud_Default", new RouteValueDictionary(new { controller = "CloudAccount", action = "Login" }));
            }
        }


        private const string CurrentCloudUserKey = "CurrentCloudUser";
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var request = MvcHelper.MakeRequest();
            if (!string.IsNullOrWhiteSpace(request.Area)
                && "Cloud".NbEquals(request.Area))
            {
                string name = (string)HttpContext.Current.Session[CurrentCloudUserKey];
                return !string.IsNullOrWhiteSpace(name);
            }

            return base.AuthorizeCore(httpContext);
        }
    }

}
